package 力扣日常刷题.木23一月.第03天303;

import 力扣日常刷题.ListNode;

/**
 * @author 帅小伙
 * @date 2022/3/3
 * @description
 */
public class Demo28合并两个排序的链表 {


    // 迭代
    public ListNode mergeTwoLists(ListNode l1,ListNode l2) {
        ListNode node = new ListNode(0);
        ListNode head = node;

        while(l1!= null && l2 != null) {
            if(l1.val < l2.val) {
                node.next = new ListNode(l1.val);
                l1 = l1.next;
            }else{
                node.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            node = node.next;
        }

        node.next = l1 == null ? l2: l1;
        return head.next;
    }


    // 递归
    public ListNode mergeTwoLists2(ListNode l1,ListNode l2) {
        if(l1 == null)return l2;
        else if(l2 == null) return l1;
        else if(l1.val > l2.val){
            l2.next = mergeTwoLists2(l1,l2.next);
            return l2;
        }else{
            l1.next = mergeTwoLists2(l1.next,l2);
            return l1;
        }
    }

}
